package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            String bucketName = minioConstantProperties.getBucketName();
            BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
            boolean bucketExists = minioClient.bucketExists(bucketExistsArgs);
            if (!bucketExists) {
                MakeBucketArgs bucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
                minioClient.makeBucket(bucketArgs);
            }
            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
            minioClient.putObject(PutObjectArgs.builder().
                    bucket(bucketName).
                    object(filename).
                    stream(file.getInputStream(), file.getSize(), -1).
                    contentType(file.getContentType()).build());
            return String.join("/", minioConstantProperties.getEndpointUrl(), bucketName, filename);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.FILE_UPLOAD_FAIL);
        }
    }
}
